package com.salesmanager.web.utils;

import java.io.*;
import java.util.Locale;

import com.salesmanager.core.modules.html.Html;
import freemarker.template.*;

import javax.servlet.ServletContext;


public class FreeMarkerUtil {

    public static void buildHtmlFile(ServletContext context, Html html) throws IOException, TemplateException {
        Configuration freemarkerCfg = new Configuration();
        // 设置要解析的模板所在的目录，并加载模板文件
        freemarkerCfg.setServletContextForTemplateLoading(context, "/");
        freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");

        // 获取模板,并设置编码方式
        Template template = freemarkerCfg.getTemplate(new StringBuilder("WEB-INF/templates/html/").append(html.getTemplateName()).toString());
        template.setEncoding("UTF-8");

        //判断文件夹是否存在
        File htmlFileDir = new File(html.getHtmlPath());
        if (!htmlFileDir.exists()){
            htmlFileDir.mkdirs();
        }

        //
        File htmlFile = new File(html.getHtmlPath() + File.separator + html.getHtmlName());
        Writer out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(htmlFile), "UTF-8"));

        // 合并数据模型与模板
        template.process(html.getDataMap(), out);

        out.flush();
        out.close();
    }
}
